import { ref } from 'vue'
const { ipc } = window

interface UseSelectFilePathOptions {
  defaultPath?: string
  onPathSelected?: (path: string) => void
  onError?: (error: Error) => void
}

export function useSelectFilePath(options: UseSelectFilePathOptions = {}) {
  const { defaultPath = '', onPathSelected, onError } = options

  const selectedPath = ref<string>(defaultPath)
  const isSelectingPath = ref<boolean>(false)
  const showPathDialog = ref<boolean>(false)

  // 打开文件选择对话框
  const selectPath = async (): Promise<string | null> => {
    isSelectingPath.value = true

    try {
      const result = await ipc.file.selectDirectory()

      if (result.success && result.path) {
        selectedPath.value = result.path

        if (onPathSelected) {
          onPathSelected(result.path)
        }

        isSelectingPath.value = false
        return result.path
      }

      isSelectingPath.value = false
      return null
    } catch (error) {
      isSelectingPath.value = false

      if (error instanceof Error && onError) {
        onError(error)
      } else if (error instanceof Error) {
        console.error('选择路径出错:', error.message)
      }

      return null
    }
  }

  // 清除已选择的路径
  const clearPath = () => {
    selectedPath.value = ''
  }

  return {
    selectedPath,
    isSelectingPath,
    showPathDialog,
    selectPath,
    clearPath
  }
}
